import { computed, watchEffect } from 'vue'
import { currentFileAtom, fileTreeAtom, selectedKeysAtom } from '@renderer/store/jotai'

import { useAtom } from 'jotai-vue'

export default function useCurrentFolderId() {
  const [selectedKeys] = useAtom(selectedKeysAtom)
  const [fileTree] = useAtom(fileTreeAtom)
  const [currentFile] = useAtom(currentFileAtom)

  const currentFolderId = computed(() => {
    let folderId = selectedKeys.value.filter((key) => key.startsWith('folder_'))?.[0]

    if (!folderId && currentFile.value) {
      Object.values(fileTree.value).forEach((item) => {
        if (item.children?.includes(currentFile.value.id)) {
          folderId = item.data.id
        }
      })
    }

    return folderId
  })

  watchEffect(() => {
    // Ensure reactive re-evaluation of `currentFolderId` when these atoms change
    selectedKeys.value
    fileTree.value
    currentFile.value
  })

  return { currentFolderId }
}
